#!/bin/sh /etc/rc.common

START=90

USE_PROCD=1

PROG=/usr/bin/zerotier-one
CONFIG_PATH=/var/lib/zerotier-one

join_network() {
	local section="${1}"
	local id allow_managed allow_global allow_default allow_dns

	config_get id "${section}" 'id'
	config_get_bool allow_managed "${section}" 'allow_managed' 1
	config_get_bool allow_global "${section}" 'allow_global' 0
	config_get_bool allow_default "${section}" 'allow_default' 0
	config_get_bool allow_dns "${section}" 'allow_dns' 0

	if [ -n "${id}" ]; then
		# an (empty) config file will cause ZT to join a network
		touch "${CONFIG_PATH}"/networks.d/"${id}".conf
		echo "allowManaged=${allow_managed}" > "${CONFIG_PATH}"/networks.d/"${id}".local.conf
		echo "allowGlobal=${allow_global}" >> "${CONFIG_PATH}"/networks.d/"${id}".local.conf
		echo "allowDefault=${allow_default}" >> "${CONFIG_PATH}"/networks.d/"${id}".local.conf
		echo "allowDNS=${allow_dns}" >> "${CONFIG_PATH}"/networks.d/"${id}".local.conf
	fi
}

start_service() {
	config_load zerotier
	local enabled port secret local_conf_path config_path copy_config_path
	local args=""

	config_get_bool enabled 'global' 'enabled' 0
	config_get port 'global' 'port'
	config_get secret 'global' 'secret'
	config_get local_conf_path 'global' 'local_conf_path'
	config_get config_path 'global' 'config_path'
	config_get_bool copy_config_path 'global' 'copy_config_path' 0

	if [ ${enabled} -eq 0 ]; then
		echo "disabled in /etc/config/zerotier"
		return
	fi

	# Remove existing link or folder
	rm -rf "${CONFIG_PATH}"

	# Create link or copy files from config_path to CONFIG_PATH
	if [ -n "${config_path}" ]; then
		if [ ! -d "${config_path}" ]; then
			echo "ZeroTier config_path does not exist: ${config_path}" 1>&2
			return
		fi

		if [ ${copy_config_path} -eq 1 ]; then
			cp -r "${config_path}" "${CONFIG_PATH}"
		else
			ln -s "${config_path}" "${CONFIG_PATH}"
		fi
	fi

	mkdir -p "${CONFIG_PATH}"/networks.d
	config_foreach join_network network

	if [ -f "${local_conf_path}" ]; then
		ln -s "${local_conf_path}" "${CONFIG_PATH}"/local.conf
	fi

	if [ -n "${port}" ]; then
		args="${args} -p${port}"
	fi

	if [ -z "${secret}" ]; then
		echo -n "Generating secret - please wait... "
		secret="$(zerotier-idtool generate)"
		[ ${?} -ne 0 ] && return 1
		uci set zerotier.global.secret="${secret}"
		uci commit zerotier
		echo "done."
	fi

	if [ -n "${secret}" ]; then
		echo "${secret}" > "${CONFIG_PATH}"/identity.secret
		# make sure there is not previous identity.public
		rm -f "${CONFIG_PATH}"/identity.public
	fi

	procd_open_instance
	procd_set_param command ${PROG} ${args}
	procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance
}

stop_service() {
	rm -rf "${CONFIG_PATH}"
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger 'zerotier'
}
